package com.example.yichuangyun.ui.activity.business;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityAddBusinessBinding;
import com.example.yichuangyun.http.ApiFactory;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.FileModel;
import com.example.yichuangyun.model.business.AddBusinessModel;
import com.example.yichuangyun.model.business.BusinessSourceModel;
import com.example.yichuangyun.model.business.CompanyAndProductModel;
import com.example.yichuangyun.model.business.ProductModel;
import com.example.yichuangyun.model.contacts.ContactPersonModel;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.AddContactAdapter;
import com.example.yichuangyun.ui.adapter.CompanyAndProductAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 新增商机
 */
@SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged"})
public class AddBusinessActivity extends BaseActivity<ActivityAddBusinessBinding, BaseViewModel> implements View.OnClickListener {

    private ActivityResultLauncher<Intent> launcherResult;
    private ActivityResultLauncher<Intent> requestAddProduct;
    private ActivityResultLauncher<Intent> requestAddSource;
    private CompanyAndProductAdapter companyAndProductAdapter;
    private final List<CompanyAndProductModel> companyAndProductData = new ArrayList<>();
    private CompanyAndProductModel companyAndProductModel;

    /**
     * 联系人信息
     */
    private final List<ContactPersonModel> contactPersonData = new ArrayList<>();
    private final List<FileModel> imgList = new ArrayList<>();
    private Bundle bundle;
    private String contactId;

    /**
     * 商机来源
     */
    private HashSet<ProductNodeModel> sourceData = new HashSet<>();
    private final List<BusinessSourceModel> sourceList = new ArrayList<>();

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        launcherResult = createActivityResultLauncher();
        bundle = getIntent().getExtras();
        if (null != bundle) {
            initTitleBar(getString(R.string.transform_business));
            contactId = bundle.getString(Constant.idKey);
            String name = bundle.getString(Constant.nameKey);
            int sex = bundle.getInt(Constant.sexKey);
            List<ContactWayModel> contactsWayList = (List<ContactWayModel>) bundle.getSerializable(Constant.listKey);
            contactPersonData.add(new ContactPersonModel(name, sex, 1, contactsWayList));
            companyAndProductData.add(new CompanyAndProductModel(contactId));
        } else {
            initTitleBar(getString(R.string.new_add_business));
            contactPersonData.add(new ContactPersonModel(1));
            companyAndProductData.add(new CompanyAndProductModel());
        }
        requestAddProduct = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    List<ProductModel> productList = new ArrayList<>();
                    HashSet<ProductNodeModel> productData = (HashSet<ProductNodeModel>) result.getData().getSerializableExtra(Constant.listKey);
                    for (ProductNodeModel productNodeModel : productData) {
                        ProductModel productModel = new ProductModel(productNodeModel.getParentId(), productNodeModel.getProductid(), productNodeModel.getTitle(), productNodeModel.getType(), productNodeModel.getPoolid());
                        productList.add(productModel);
                    }
                    companyAndProductModel.setProducts(productList);
                    companyAndProductAdapter.notifyDataSetChanged();
                    changeBtnStatus();
                }
            }
        });
        requestAddSource = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    sourceList.clear();
                    sourceData = (HashSet<ProductNodeModel>) result.getData().getSerializableExtra(Constant.listKey);
                    for (ProductNodeModel productNodeModel : sourceData) {
                        BusinessSourceModel businessSourceModel = new BusinessSourceModel(productNodeModel.getId(), productNodeModel.getTitle());
                        sourceList.add(businessSourceModel);
                    }
                    binding.tvBusinessFrom.setText(sourceList.get(0).getSource());
                    changeBtnStatus();
                }
            }
        });
    }

    @Override
    public void initCtrl() {
        companyAndProductAdapter = new CompanyAndProductAdapter(context, companyAndProductData, this::changeBtnStatus, contactId);
        binding.recyclerView.setAdapter(companyAndProductAdapter);
        AddContactAdapter addContactAdapter = new AddContactAdapter(context, contactPersonData, list -> changeBtnStatus(), 1);
        binding.contactRecyclerView.setAdapter(addContactAdapter);
    }

    @Override
    protected void initClick() {
        binding.rlBusinessFrom.setOnClickListener(this);
        binding.rlUploadImg.setOnClickListener(this);
        binding.ivDelete.setOnClickListener(this);
        binding.btnConfirm.setOnClickListener(this);
        companyAndProductAdapter.setOnChooseProductListener((model, category) -> {
            CommonUtil.closeKeyboard(AddBusinessActivity.this);
            companyAndProductModel = model;
            if (CommonUtil.isCanClick()) {
                Intent intent = new Intent(AddBusinessActivity.this, ProductActivity.class);
                Bundle bundle = new Bundle();
                HashSet<ProductNodeModel> productData = new HashSet<>();
                if (companyAndProductModel.getProducts() != null && companyAndProductModel.getProducts().size() > 0) {
                    for (ProductModel productModel : companyAndProductModel.getProducts()) {
                        productData.add(new ProductNodeModel(productModel.getProductName(), productModel.getId(), productModel.getParentId(), productModel.getProductId(), productModel.getPoolId(), productModel.getType(), 0, productModel.getParentProductId()));
                    }
                }
                bundle.putSerializable(Constant.listKey, productData);
                bundle.putInt(Constant.categoryKey, category);
                intent.putExtras(bundle);
                requestAddProduct.launch(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        CommonUtil.closeKeyboard(this);
        int id = v.getId();// 商机来源
        if (id == R.id.rl_business_from) {
            Intent intent = new Intent(AddBusinessActivity.this, ProductActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.flagKey, 1);
            bundle.putSerializable(Constant.listKey, sourceData);
            intent.putExtras(bundle);
            requestAddSource.launch(intent);
        } else if (id == R.id.rl_upload_img) {
            PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setSelectorUIStyle(new PictureSelectorStyle())
                    .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                    .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100)
                            .setCompressListener(new OnNewCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(String source, File compressFile) {
                                    if (call != null) {
                                        call.onCallback(source, compressFile.getAbsolutePath());
                                    }
                                }

                                @Override
                                public void onError(String source, Throwable e) {
                                    if (call != null) {
                                        call.onCallback(source, null);
                                    }
                                }
                            }).launch())
                    .forResult(launcherResult);
        } else if (id == R.id.iv_delete) {
            binding.rlImgInfo.setVisibility(View.GONE);
            imgList.clear();
        } else if (id == R.id.btn_confirm) {
            boolean isNoCreditNo = false;
            for (CompanyAndProductModel companyAndProductModel : companyAndProductData) {
                if (companyAndProductModel.getServiceCategory() == 0 && TextUtils.isEmpty(companyAndProductModel.getCreditNo())) {
                    isNoCreditNo = true;
                    companyAndProductModel.setCompName("");
                }
            }
            companyAndProductAdapter.notifyDataSetChanged();
            if (isNoCreditNo) {
                ToastHelper.show(getString(R.string.input_company_name));
                return;
            }
            save();
        }
    }

    /**
     * 添加商机
     */
    private void save() {
        UMengUtil.setCountEventId(Constant.SAVE_BUSINESS);
        showLoadingDialog();
        AddBusinessModel addBusinessModel = new AddBusinessModel();
        addBusinessModel.setCompanys(companyAndProductData);
        addBusinessModel.setSourceLists(sourceList);
        addBusinessModel.setAppTels(contactPersonData);
        addBusinessModel.setClueRecordRefs(imgList);
        Log.e("@添加商机入参：", new Gson().toJson(addBusinessModel));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(addBusinessModel));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().saveBusiness(requestBody), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (stringHttpRespond.code == Constant.SUCCESS) {
                    ToastHelper.show(getString(R.string.add_business_success));
                    EventBus.getDefault().post(new EventBusModel(bundle == null ? Constant.refreshMainBusinessList : Constant.refreshContactDetailsBusinessList));
                    AddBusinessActivity.this.finish();
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                ToastHelper.show(e.getMessage());
                dismissLoadingDialog();
            }
        });
    }

    private void uploadImg(File file) {
        showLoadingDialog();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        try {
            // 路径有中文名要进行编码
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", URLEncoder.encode(file.getName(), "utf-8"), requestBody);
            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadImage(part), new MyObserver<HttpRespond<String>>() {
                @Override
                protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                    if (Constant.SUCCESS == stringHttpRespond.code) {
                        if (!TextUtils.isEmpty(stringHttpRespond.data)) {
                            imgList.clear();
                            imgList.add(new FileModel(file.getName(), ApiFactory.IMAGE_UPLOAD + stringHttpRespond.data, 1));
                            binding.rlImgInfo.setVisibility(View.VISIBLE);
                            binding.tvImgName.setText(file.getName());
                        } else {
                            ToastHelper.show(stringHttpRespond.msg);
                        }
                    }
                    dismissLoadingDialog();
                }

                @Override
                protected void onFail(Throwable e) {
                    dismissLoadingDialog();
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void changeBtnStatus() {
        Log.e("@@@@@@changeBtnStatus", new Gson().toJson(companyAndProductData));
        boolean isALlContact = true;
        for (int i = 0; i < contactPersonData.size(); i++) {
            if (TextUtils.isEmpty(contactPersonData.get(i).getName()) || contactPersonData.get(i).getSex() == 0) {
                isALlContact = false;
            }
            for (int j = 0; j < contactPersonData.get(i).getTels().size(); j++) {
                ContactWayModel contactWayModel = contactPersonData.get(i).getTels().get(j);
                if (TextUtils.isEmpty(contactWayModel.getInfo())) {
                    isALlContact = false;
                } else {
                    if (contactWayModel.getType() == 1) {
                        if (contactWayModel.getInfo().length() < 11 || !contactWayModel.getInfo().startsWith("1")) {
                            isALlContact = false;
                        }
                    }
                    if (contactWayModel.getType() == 4 && !CommonUtil.isEmail(contactWayModel.getInfo())) {
                        isALlContact = false;
                    }
                }
            }
        }

        boolean isALlCompanyAndProduct = true;
        for (CompanyAndProductModel companyAndProductModel : companyAndProductData) {
            if (companyAndProductModel.getProducts() == null || companyAndProductModel.getProducts().size() == 0 || TextUtils.isEmpty(companyAndProductModel.getChanceWeight())) {
                isALlCompanyAndProduct = false;
            }
            if (companyAndProductModel.getServiceCategory() == 0 && TextUtils.isEmpty(companyAndProductModel.getCompName())) {
                isALlCompanyAndProduct = false;
            }
        }

        if (!TextUtils.isEmpty(binding.tvBusinessFrom.getText().toString()) && isALlContact && isALlCompanyAndProduct) {
            binding.btnConfirm.setEnabled(true);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    uploadImg(file);
                }
            }
        });
    }
}